package com.liu.my_blog_system.service.impl;

import com.liu.my_blog_system.entity.TbUser;
import com.liu.my_blog_system.service.TbUserService;
import com.liu.my_blog_system.utils.Constants;
import com.liu.my_blog_system.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author liuchengjie
 */
@Service("permission")
public class PermissionService {

    @Autowired
    private TbUserService userService;
    /**
     * 判断是否为管理员
     * @return
     */
    public boolean admin() {
        //从容器中拿到request和response
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        String token_key = CookieUtils.getTokenInCookie(request, Constants.User.KEY_BLOG_TOKEN);
        //判断令牌key
        if (ObjectUtils.isEmpty(token_key)) {
            return false;
        }
        Map map = userService.checkUserStatus(request, response);
        TbUser userInfo =(TbUser) map.get("userInfo");
        if (userInfo == null) {
            return false;
        }
        if (Constants.User.ADMIN.equals(userInfo.getRoles())) {
            return true;
        }
        return false;
    }
}
